﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SafEditor.cs" company="Collaboris Ltd.">
//   Copyright (c) Collaboris Ltd. All rights Reserved.
// </copyright>
// <summary>
//   
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Collaboris.Saf.Registrations
{
    using System;

    using Spring.Validation;

    public abstract class SafEditor<T>
    {
        readonly Type editedType;

        private ValidatorGroup validatorGroup;

        public SafEditor()
        {
            this.editedType = typeof(T);
        }

        // this method will be called when the editor is about to 
        // be closed.
        // it will return a dictionary of all the values that 
        // have been entered onto the screen.
        public virtual ValidationErrors Validate()
        {
            if (this.Validator != null)
            {
                T instance = this.CreateInstanceFromEditor();
                ValidationErrors errors = new ValidationErrors();
                
                this.Validator.Validate(instance, errors);

                return errors;
            }

            return null;
        }

        protected abstract T CreateInstanceFromEditor();

        public abstract void Render();

        public ValidatorGroup Validator
        {
            get
            {
                if (this.validatorGroup == null)
                {
                    this.validatorGroup = SafTypeRegistryCache.GetValidator(editedType);
                }

                return validatorGroup;
            }

            set
            {
                validatorGroup = value;
            }
        }
    }
}